package com.lut.single;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * @author liuning
 * @ProjectName SingleModel
 * @time 2021/12/13 17:50
 */
//懒汉式单例模式
public class LazyMan {

    private static boolean flag = false;

    private LazyMan(){
        synchronized (LazyMan.class){
            if (flag == false){
                flag = true;
            }else {
                throw new RuntimeException("不要试图使用反射破坏异常");
            }
        }
        System.out.println(Thread.currentThread().getName()+"ok");
    }
    private volatile static LazyMan lazyMan;
    //单线程是ok的
    //双重检测锁模式的懒汉式单例   DCL懒汉式
    public static LazyMan getInstance(){
        if(lazyMan == null){
            synchronized (LazyMan.class){
                if(lazyMan == null){
                    lazyMan = new LazyMan();//不是一个原子性操作
                    /**
                     * 1、分配内存空间
                     * 2、执行构造方法，初始化对象
                     * 3、把这个对象指向这个空间
                     * 容易出现问题：A线程可能占用了一个空间，但是并没有完成初始化
                     * 因此需要使用关键字volatile
                     */
                }
            }
        }
        return lazyMan;
    }
    //反射
    public static void main(String[] args) throws Exception {
        //LazyMan instance = LazyMan.getInstance();
        Field flag = LazyMan.class.getDeclaredField("flag");
        flag.setAccessible(true);

        Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);//无视私有构造器
        LazyMan instance = declaredConstructor.newInstance();
        flag.set(instance,false);

        LazyMan instance2 = declaredConstructor.newInstance();
        System.out.println(instance);
        System.out.println(instance2);
    }
}
